package com.xsth.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * 存储文件的数据库 副数据库
 * 
 * @author liulinsen
 *
 */
@Configuration
// 扫描 Mapping 接口并容器管理
@MapperScan(basePackages = AssistantDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "assistantSqlSessionFactory")
public class AssistantDataSourceConfig {
	// 精确到 assistant 目录，以便跟其他数据源隔离
	static final String PACKAGE = "com.xsth.mapping.assistant";
	static final String MAPPER_LOCATION = "classpath:mapper/assistant/*.xml";

	@Value("${assistant.datasource.url}")
	private String url;

	@Value("${assistant.datasource.username}")
	private String user;

	@Value("${assistant.datasource.password}")
	private String password;

	@Value("${assistant.datasource.driverClassName}")
	private String driverClass;

	@Bean(name = "assistantDataSource")
	public DataSource assistantDataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(driverClass);
		dataSource.setUrl(url);
		dataSource.setUsername(user);
		dataSource.setPassword(password);
		return dataSource;
	}

	/**
	 * 事务管理
	 * 
	 * @return
	 */
	@Bean(name = "assistantTransactionManager")
	public DataSourceTransactionManager assistantTransactionManager() {
		return new DataSourceTransactionManager(assistantDataSource());
	}

	@Bean(name = "assistantSqlSessionFactory")
	public SqlSessionFactory assistantSqlSessionFactory(
			@Qualifier("assistantDataSource") DataSource assistantDataSource) throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(assistantDataSource);
		sessionFactory.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources(AssistantDataSourceConfig.MAPPER_LOCATION));
		return sessionFactory.getObject();
	}
}
